package com.sailing.lianxi.thread.pattern;

import static org.hamcrest.CoreMatchers.not;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CountDownLatch;

public class Coordinator {

	public static final Object POISON_PILL = new Object();
	private int productCount = 3;
	private int consumerCount = 5;
	
	
	public void startAll() {
		BlockingQueue<Object> queue = new ArrayBlockingQueue<Object>(20);
		try {
			CountDownLatch noMoreToProduce = new CountDownLatch(productCount);
			//start consumer
			for(int i=0;i<consumerCount;i++) {
				new Thread(new Consumer("consumer"+i, queue)).start();
			}
			//start producer
			for(int i=0;i<productCount;i++) {
				new Thread(new Producer("producer"+i, noMoreToProduce, queue)).start();
			}
			//wait until all producer down
			noMoreToProduce.await();
			System.out.println("All producer finished putting POISON_PILL to the queue to stop consumer");
			//put poison pill
			queue.put(POISON_PILL);
		} catch (Exception e) {
		}
		
	}
	
	public static void main(String[] args) {
		new Coordinator().startAll();
	}
}
